<script setup>
import {ref} from 'vue';
import {selectFieldsApi} from "/src/api/business/super-computer/datasource/select-fields-api.js";
import {message} from "ant-design-vue";
import {useRouter} from "vue-router";

let fields = ref([]);
let targetKeys = ref([{}]);
let items = ref([]);
let emits = defineEmits(['reloadList']);
const sourceId = ref("");

// 定义获取字段的方法
async function fetchData(sourceId1, tableName) {
  try {
    sourceId.value = sourceId1;
    const response = await selectFieldsApi.queryFields(tableName);
    console.log(response.data);
    
    items.value = response.data;
    fields.value = [];

    if (items.value.length > 0) {
      items.value.forEach(item => {
        fields.value.push({
          key: item.column_name,
          title: item.column_name,
          description: item.data_type,
          chosen: false
        })
      })
    }
    targetKeys.value = fields.value.filter(item => item.chosen).map(item => item.key);
  } catch (error) {
    console.error("There was an error fetching the fields!", error);
  }
}


// 处理穿梭框变化
let data = ref({});
const handleChange = (keys) => {
  let selectedFields = ref("")

  keys.forEach(key => {
    selectedFields.value += key + ","
  })
  data.value = {};


  keys.forEach(key => {
    //存入data，键为targetKeysKey，值为item.DATA_TYPE
    items.value.forEach(item => {
      if (key === item.column_name) {
        data.value[key] = item.data_type;
      }
    })
  })
};

//---------------显示与隐藏---------------
const open = ref(false);
const confirmLoading = ref(false);

function showModalFields(sourceId, tableName) {
  fetchData(sourceId, tableName);
  open.value = true;
}

const handleOk = () => {
  confirmLoading.value = true;
  setTimeout(() => {
    open.value = false;
    confirmLoading.value = false;
  }, 100);
};

defineExpose({
  showModalFields
});


const save = () => {
  selectFieldsApi.saveColumns(data.value, sourceId.value).then(message.success("保存成功"))
  handleOk();
}

</script>

<template>

  <a-modal
      v-model:open="open"
      title="请选择字段"
      :confirm-loading="confirmLoading"
      @ok="save"
      z-index="1000"
      ok-text="下一步"
  >
    <a-transfer
        v-model:target-keys="targetKeys"
        :data-source="fields.values()"
        show-search
        :list-style="{
      width: '400px',
      height: '500px',
    }"
        operationStyle=""
        :render="item => `${item.title}`"
        @change="handleChange"
    >
      <template #notFoundContent>
        <span>未查询到此字段</span>
      </template>
    </a-transfer>
  </a-modal>

</template>

<style scoped lang="less">

</style>